import { ref, computed } from 'vue'

export function useChessGame({ 
  gameTime, 
  moveHistory, 
  capturedPieces, 
  moveStack,
  addMove,
  addCapture,
  undoMove 
}) {
  const initialBoard = [
    ['black-rook', 'black-knight', 'black-bishop', 'black-queen', 'black-king', 'black-bishop', 'black-knight', 'black-rook'],
    ['black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn', 'black-pawn'],
    Array(8).fill(null),
    Array(8).fill(null),
    Array(8).fill(null),
    Array(8).fill(null),
    ['white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn', 'white-pawn'],
    ['white-rook', 'white-knight', 'white-bishop', 'white-queen', 'white-king', 'white-bishop', 'white-knight', 'white-rook']
  ]

  const board = ref(initialBoard)
  const selectedPiece = ref(null)
  const currentPlayer = ref('white')
  const validMoves = ref([])
  const gameHistory = ref([])
  const isCheck = ref(false)
  const isCheckmate = ref(false)
  const canCastle = ref({
    white: { kingside: true, queenside: true },
    black: { kingside: true, queenside: true }
  })
  const lastMove = ref(null)

  const getPiece = (row, col) => {
    return board.value[row][col]
  }

  const isValidMove = (row, col) => {
    return validMoves.value.some(move => 
      move.row === row && move.col === col
    )
  }

  const isInBoard = (row, col) => {
    return row >= 0 && row < 8 && col >= 0 && col < 8
  }

  const canMoveTo = (row, col, piece) => {
    const targetPiece = board.value[row][col]
    if (!targetPiece) return true
    return targetPiece.includes(piece.includes('white') ? 'black' : 'white')
  }

  const calculateValidMoves = (row, col) => {
    const piece = board.value[row][col]
    const moves = []
    
    if (!piece) return moves

    const pieceType = piece.split('-')[1]
    const isWhite = piece.includes('white')

    switch (pieceType) {
      case 'pawn':
        const direction = isWhite ? -1 : 1
        const startRow = isWhite ? 6 : 1

        if (isInBoard(row + direction, col) && !board.value[row + direction][col]) {
          moves.push({ row: row + direction, col })
          
          if (row === startRow && !board.value[row + direction * 2][col]) {
            moves.push({ row: row + direction * 2, col })
          }
        }

        const captureColumns = [col - 1, col + 1]
        captureColumns.forEach(captureCol => {
          if (isInBoard(row + direction, captureCol)) {
            const targetPiece = board.value[row + direction][captureCol]
            if (targetPiece && targetPiece.includes(isWhite ? 'black' : 'white')) {
              moves.push({ row: row + direction, col: captureCol })
            }
          }
        })
        break

      case 'rook':
        const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
        directions.forEach(([dr, dc]) => {
          let newRow = row + dr
          let newCol = col + dc
          while (isInBoard(newRow, newCol)) {
            if (!board.value[newRow][newCol]) {
              moves.push({ row: newRow, col: newCol })
            } else {
              if (board.value[newRow][newCol].includes(isWhite ? 'black' : 'white')) {
                moves.push({ row: newRow, col: newCol })
              }
              break
            }
            newRow += dr
            newCol += dc
          }
        })
        break

      case 'knight':
        const knightMoves = [
          [-2, -1], [-2, 1], [-1, -2], [-1, 2],
          [1, -2], [1, 2], [2, -1], [2, 1]
        ]
        knightMoves.forEach(([dr, dc]) => {
          const newRow = row + dr
          const newCol = col + dc
          if (isInBoard(newRow, newCol) && canMoveTo(newRow, newCol, piece)) {
            moves.push({ row: newRow, col: newCol })
          }
        })
        break

      case 'bishop':
        const bishopDirections = [[1, 1], [1, -1], [-1, 1], [-1, -1]]
        bishopDirections.forEach(([dr, dc]) => {
          let newRow = row + dr
          let newCol = col + dc
          while (isInBoard(newRow, newCol)) {
            if (!board.value[newRow][newCol]) {
              moves.push({ row: newRow, col: newCol })
            } else {
              if (board.value[newRow][newCol].includes(isWhite ? 'black' : 'white')) {
                moves.push({ row: newRow, col: newCol })
              }
              break
            }
            newRow += dr
            newCol += dc
          }
        })
        break

      case 'queen':
        const queenDirections = [
          [0, 1], [0, -1], [1, 0], [-1, 0],
          [1, 1], [1, -1], [-1, 1], [-1, -1]
        ]
        queenDirections.forEach(([dr, dc]) => {
          let newRow = row + dr
          let newCol = col + dc
          while (isInBoard(newRow, newCol)) {
            if (!board.value[newRow][newCol]) {
              moves.push({ row: newRow, col: newCol })
            } else {
              if (board.value[newRow][newCol].includes(isWhite ? 'black' : 'white')) {
                moves.push({ row: newRow, col: newCol })
              }
              break
            }
            newRow += dr
            newCol += dc
          }
        })
        break

      case 'king':
        const kingDirections = [
          [0, 1], [0, -1], [1, 0], [-1, 0],
          [1, 1], [1, -1], [-1, 1], [-1, -1]
        ]
        kingDirections.forEach(([dr, dc]) => {
          const newRow = row + dr
          const newCol = col + dc
          if (isInBoard(newRow, newCol) && canMoveTo(newRow, newCol, piece)) {
            moves.push({ row: newRow, col: newCol })
          }
        })
        break
    }

    return moves
  }

  const selectPiece = (row, col) => {
    const piece = board.value[row][col]
    if (!piece || !piece.includes(currentPlayer.value)) {
      return
    }
    
    selectedPiece.value = { row, col }
    validMoves.value = calculateValidMoves(row, col)
  }

  const isKingInCheck = (color, testBoard = board.value) => {
    let kingPosition
    for (let row = 0; row < 8; row++) {
      for (let col = 0; col < 8; col++) {
        if (testBoard[row][col] === `${color}-king`) {
          kingPosition = { row, col }
          break
        }
      }
      if (kingPosition) break
    }

    const opponentColor = color === 'white' ? 'black' : 'white'
    for (let row = 0; row < 8; row++) {
      for (let col = 0; col < 8; col++) {
        const piece = testBoard[row][col]
        if (piece && piece.includes(opponentColor)) {
          const moves = calculateValidMoves(row, col, testBoard, true)
          if (moves.some(move => move.row === kingPosition.row && move.col === kingPosition.col)) {
            return true
          }
        }
      }
    }
    return false
  }

  const willMoveExposeKing = (fromRow, fromCol, toRow, toCol) => {
    const piece = board.value[fromRow][fromCol]
    const color = piece.includes('white') ? 'white' : 'black'
    
    const testBoard = board.value.map(row => [...row])
    testBoard[toRow][toCol] = testBoard[fromRow][fromCol]
    testBoard[fromRow][fromCol] = null

    return isKingInCheck(color, testBoard)
  }

  const handleCastling = (kingRow, kingCol, toRow, toCol) => {
    const color = board.value[kingRow][kingCol].includes('white') ? 'white' : 'black'
    const isKingside = toCol > kingCol

    if (isKingside) {
      board.value[kingRow][kingCol + 1] = board.value[kingRow][7]
      board.value[kingRow][7] = null
    } else {
      board.value[kingRow][kingCol - 1] = board.value[kingRow][0]
      board.value[kingRow][0] = null
    }

    canCastle.value[color].kingside = false
    canCastle.value[color].queenside = false
  }

  const canDoCastling = (kingRow, kingCol, color) => {
    const moves = []
    
    if (canCastle.value[color].kingside && 
        !board.value[kingRow][kingCol + 1] && 
        !board.value[kingRow][kingCol + 2] &&
        board.value[kingRow][7]?.includes('rook')) {
      moves.push({ row: kingRow, col: kingCol + 2, special: 'castle-kingside' })
    }
    
    if (canCastle.value[color].queenside && 
        !board.value[kingRow][kingCol - 1] && 
        !board.value[kingRow][kingCol - 2] && 
        !board.value[kingRow][kingCol - 3] &&
        board.value[kingRow][0]?.includes('rook')) {
      moves.push({ row: kingRow, col: kingCol - 2, special: 'castle-queenside' })
    }

    return moves
  }

  const handlePawnPromotion = (row, col) => {
    const piece = board.value[row][col]
    if (piece?.includes('pawn') && (row === 0 || row === 7)) {
      const color = piece.includes('white') ? 'white' : 'black'
      board.value[row][col] = `${color}-queen`
    }
  }

  const handleEnPassant = (fromRow, fromCol, toRow, toCol) => {
    if (lastMove.value?.piece?.includes('pawn') && 
        Math.abs(lastMove.value.fromRow - lastMove.value.toRow) === 2) {
      const piece = board.value[fromRow][fromCol]
      if (piece?.includes('pawn')) {
        const direction = piece.includes('white') ? -1 : 1
        if (toRow === lastMove.value.toRow + direction && toCol === lastMove.value.toCol) {
          board.value[lastMove.value.toRow][lastMove.value.toCol] = null
        }
      }
    }
  }

  const movePiece = (toRow, toCol) => {
    if (!selectedPiece.value || !isValidMove(toRow, toCol)) {
      return
    }

    const { row: fromRow, col: fromCol } = selectedPiece.value
    const piece = board.value[fromRow][fromCol]
    const moveInfo = validMoves.value.find(move => 
      move.row === toRow && move.col === toCol
    )

    if (willMoveExposeKing(fromRow, fromCol, toRow, toCol)) {
      return
    }

    const capturedPiece = board.value[toRow][toCol]

    board.value[toRow][toCol] = piece
    board.value[fromRow][fromCol] = null

    if (moveInfo?.special) {
      switch (moveInfo.special) {
        case 'castle-kingside':
        case 'castle-queenside':
          handleCastling(fromRow, fromCol, toRow, toCol)
          break
        case 'en-passant':
          handleEnPassant(fromRow, fromCol, toRow, toCol)
          break
      }
    }

    handlePawnPromotion(toRow, toCol)

    lastMove.value = {
      piece,
      fromRow,
      fromCol,
      toRow,
      toCol
    }
    gameHistory.value.push(lastMove.value)

    const result = {
      needsPromotion: piece.includes('pawn') && (toRow === 0 || toRow === 7),
      color: piece.includes('white') ? 'white' : 'black'
    }

    if (capturedPiece && addCapture) {
      addCapture(capturedPiece)
    }

    if (addMove) {
      const pieceType = piece.split('-')[1]
      const fromSquare = `${String.fromCharCode(97 + fromCol)}${8 - fromRow}`
      const toSquare = `${String.fromCharCode(97 + toCol)}${8 - toRow}`
      addMove(fromSquare, toSquare, pieceType, capturedPiece)
    }

    validMoves.value = []
    selectedPiece.value = null
    currentPlayer.value = currentPlayer.value === 'white' ? 'black' : 'white'

    isCheck.value = isKingInCheck(currentPlayer.value)
    if (isCheck.value) {
      isCheckmate.value = checkForCheckmate()
    }

    return result
  }

  const checkForCheckmate = () => {
    const color = currentPlayer.value
    for (let row = 0; row < 8; row++) {
      for (let col = 0; col < 8; col++) {
        const piece = board.value[row][col]
        if (piece && piece.includes(color)) {
          const moves = calculateValidMoves(row, col)
          const validMoves = moves.filter(move => 
            !willMoveExposeKing(row, col, move.row, move.col)
          )
          if (validMoves.length > 0) {
            return false
          }
        }
      }
    }
    return true
  }

  return {
    board,
    selectedPiece,
    validMoves,
    getPiece,
    isValidMove,
    selectPiece,
    movePiece,
    isCheck,
    isCheckmate,
    gameHistory,
    lastMove,
    currentPlayer,
    calculateValidMoves
  }
} 